// 统一请求封装
import axios, { AxiosRequestConfig, AxiosInstance } from "axios"
import NProgress from "nprogress"
import "nprogress/nprogress.css"
import { useUserStore } from "@/store/user"
// 获取axios请求实例
const instance: AxiosInstance = axios.create({
	baseURL: "/api",
	timeout: 10000
})

// 请求拦截器
instance.interceptors.request.use(
	(config): any | AxiosRequestConfig<any> => {
		const newConfig: any | AxiosRequestConfig<any> = { ...config }
		// 获取要带入的后台参数
		const userStore = useUserStore()
		const token =
			userStore.token || JSON.parse(localStorage.getItem("token") as any)
		// 设置头文件
		newConfig.headers = {
			// "Content-Type": "application/json",
			...config.headers,
			authorization: token
		}
		return newConfig
	},
	(error) => {
		return Promise.reject(error)
	}
)

// 响应拦截器
instance.interceptors.response.use(
	(response) => {
		NProgress.done()
		const { data } = response
		return data
	},
	(error) => {
		NProgress.done()
		if (error && error.response) {
			switch (error.response.status) {
				case 404:
					error.message = "错误请求"
					break
				default:
					break
			}
		}
		return Promise.reject(error)
	}
)

const request = Object.create(instance)

// 对get, post, put, delete等常用方法作了封装
request.get = function (url: string, data = {}, config = {}) {
	NProgress.start()
	return instance.get(url, { params: data, ...config })
}

request.post = function (url: string, data = {}, config = {}) {
	NProgress.start()
	return instance.post(url, data, config)
}

request.put = function (url: string, data = {}, config = {}) {
	NProgress.start()
	return instance.put(url, data, config)
}

request.delete = function (url: string, data = {}, config = {}) {
	NProgress.start()
	return instance.delete(url, { params: data, ...config })
}

export default request
